package tests.read;

import static org.junit.Assert.fail;

import java.util.ArrayList;

import model.Budget;
import model.BudgetFactory;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.workplicity.util.Helper;
import org.workplicity.worklet.WorkletContext;

import com.mongodb.BasicDBObject;
import com.mongodb.util.JSON;

/*
 * 
 * Attempts to fetch all budgets
 * 
 */

public class BudgetQueryTest00
{
	Budget budget;
	BudgetFactory factory;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception
	{
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception
	{
	}

	@Before
	public void setUp() throws Exception
	{
		factory = new BudgetFactory();
		budget = (Budget) factory.create();
        budget.setName("Test budget");
        budget.setDescription("This is a test budget.");
        budget.commit();
	}

	@After
	public void tearDown() throws Exception
	{
		Helper.delete( budget, "Budgets", WorkletContext.getInstance());
	}

	@Test
	public void test()
	{	
		try
		{
			BasicDBObject criteria = new BasicDBObject("entry.id", budget.getId());
			String predicate = JSON.serialize(criteria);
			
			@SuppressWarnings("unchecked")
			ArrayList<Budget> budgets = Helper.query("Budgets", predicate, WorkletContext.getInstance());
			
			if(budgets.size() != 0)
			{
				if(!budgets.get(0).getName().equals("Test budget"))
				{
					fail("Fetching budget failed: incorrect name");
				}
			}
			else
			{
				fail("Fetching budget failed: no results found");
			}
			
		}
		catch (Exception e)
		{
			System.out.println("-----------------------------------------------");
			
			e.printStackTrace();
			fail("Fetching budget failed with exception " + e);
		}
	}
}